package com.sc.nft.helper;


import com.sc.nft.util.TableNameContext;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 分区执行器，用于隐藏分区细节
 *
 * @author zlikun
 * @since 2024/05/31
 */
public class TablePartitionExecutor {

    public static void exec(String partition, Runnable handler) {
        if (partition == null) {
            handler.run();
            return;
        }
        try {
            TableNameContext.setPartition(partition);
            handler.run();
        } finally {
            TableNameContext.clear();
        }
    }

    public static void exec(String partition, Consumer<String> handler) {
        if (partition == null) {
            handler.accept(null);
            return;
        }
        try {
            TableNameContext.setPartition(partition);
            handler.accept(partition);
        } finally {
            TableNameContext.clear();
        }
    }

    public static <T> T exec(String partition, Supplier<T> handler) {
        if (partition == null) {
            return handler.get();
        }
        try {
            TableNameContext.setPartition(partition);
            return handler.get();
        } finally {
            TableNameContext.clear();
        }
    }

    public static <T> T exec(String partition, Function<String, T> handler) {
        if (partition == null) {
            return handler.apply(null);
        }
        try {
            TableNameContext.setPartition(partition);
            return handler.apply(partition);
        } finally {
            TableNameContext.clear();
        }
    }

}
